package org.internna.ossmoney.model.security;

import java.util.Set;
import java.util.HashSet;
import javax.persistence.Query;
import javax.persistence.Column;
import javax.persistence.FetchType;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQuery;
import javax.validation.constraints.Size;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import org.springframework.roo.addon.equals.RooEquals;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.tostring.RooToString;
import org.springframework.roo.addon.jpa.entity.RooJpaEntity;
import org.springframework.roo.addon.serializable.RooSerializable;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;

import static org.springframework.util.StringUtils.hasText;

@RooEquals
@RooJavaBean
@RooToString
@RooSerializable
@RooJpaActiveRecord
@RooJpaEntity(table = "AUTHORITY_NAMES")
@NamedQuery(name = "findByName", query = "SELECT a FROM Authority a WHERE authority = :authority")
public class Authority {

	private static final long serialVersionUID = -6913889053268285231L;

	public static final String ROLE_USER = "ROLE_USER";
    public static final String ROLE_ADMIN = "ROLE_ADMIN";

    @NotNull
    @Size(min = 6)
    @Column(unique = true)
    @Pattern(regexp = "ROLE_.*")
    private String authority;

	@ManyToMany(fetch = FetchType.LAZY, mappedBy = "roles")
    private Set<UserDetails> users = new HashSet<UserDetails>();

    public static final Authority findByName(String name) {
    	Authority authority = null;
    	if (hasText(name)) {
    		Query query =  entityManager().createNamedQuery("findByName");
    		query.setParameter("authority", name);
    		authority = (Authority) query.getSingleResult();
    	}
    	return authority;
    }

}
